﻿using GuanQL.Service.Accounts;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GanQL.Web.Infrastructure.Filters
{
    public class LogUserOperTimeFilter : IAsyncActionFilter
    {
        public AccountService _accountService;
        public readonly ILogger _logger;

        public LogUserOperTimeFilter(
            AccountService accountService,
             ILoggerFactory loggerFactory)
        {
            _accountService = accountService;
            _logger = loggerFactory.CreateLogger(nameof(LogUserOperTimeFilter));
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!context.HttpContext.User.Identity.IsAuthenticated)
            {
                await next();
                return;
            }

            await next();
            try
            {
                await _accountService.LogUserOperTime();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
            }
        }
    }
}
